package com.itheima.filter;

import com.itheima.utils.LoginJWTkey;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.io.IOException;

//调用包:import jakarta.servlet.*;
/**前端访问过滤
 * @Author:上官徵羽
 * @Date: 2025/07/16 9:47
 * @Description TODO 今日内容:
 */
@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    /** 初始化方法, web服务器启动, 创建Filter实例时调用, 只调用一次 */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /** 拦截到请求时,调用该方法,可以调用多次 */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取请求url
        String url = request.getRequestURL().toString();

        //判断请求url中是否包含login,如果包含,说明是登录操作,放行
        if (url.contains("login")){
            log.info("TokenFilter doFilter:登录操作,执行放行");
            filterChain.doFilter(request,response);
            return;
        }

        //获取请求头中的令牌(token)
        String jwt = request.getHeader("token");
        //判断令牌是否存在,如果不存在,返回错误结果(未登录)
        //StringUtils的包:org.springframework.util
        if (!StringUtils.hasLength(jwt)){
            log.info("TokenFilter doFilter:未持有通关文凭,禁止通行");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //解析token,如果解析失败,返回错误结果,未登录
        try {
            Claims claims = LoginJWTkey.parsingEmpJWT(jwt);
            //把解析出来的数据存入中间类
            CurrentHolder.setCurrentHolder(claims);
        }catch (Exception e){
            e.printStackTrace();
            log.info("TokenFilter doFilter:通关文牒失效,禁止通行");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }

        //放行
        log.info("TokenFilter doFilter:持有合法且有效通关文牒,放行!");
        filterChain.doFilter(request,response);
    }

    /** 销毁方法, web服务器关闭时调用, 只调用一次 */
    @Override
    public void destroy() {
        CurrentHolder.removeCurrentHolder();
        Filter.super.destroy();
    }
}
